package com.yuntianshi.controller;

import com.yuntianshi.common.*;
import com.yuntianshi.config.MinioConfig;
import com.yuntianshi.pojo.Order;
import com.yuntianshi.service.OrderService;
import com.yuntianshi.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig prop;
//    @Autowired
//    private JedisPool jedisPool;

    /**
     * 预约
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER
        String codeInRedis = redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //String codeInRedis = jedisPool.getResource().get(
                //telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            return new Result(false, MessageContant.VALIDATECODE_ERROR);
        }
        Result result =null;
        //调用体检预约服务
        try{
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result = orderService.order(map);
        }catch (Exception e){
            e.printStackTrace();
            //预约失败
            return result;
        }
        if(result.isFlag()){
            //预约成功，发送短信通知
//            String orderDate = (String) map.get("orderDate");
//            try {
//                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
//            } catch (ClientException e) {
//                e.printStackTrace();
//            }
            System.out.println("预约成功");
        }
        return result;
    }
    /**
     * 根据id查询预约信息，包括套餐信息和会员信息
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Order order = orderService.findById(id);
            //查询预约信息成功
            return new Result(true,MessageContant.QUERY_ORDER_SUCCESS,order);
        }catch (Exception e){
            e.printStackTrace();
            //查询预约信息失败
            return new Result(false,MessageContant.QUERY_ORDER_FAIL);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception{
        PageResult pageResult = orderService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Map map,Integer[] setmealIds){
        Result result=null;
        try {
            if (!(setmealIds!=null&&setmealIds.length>0)){
                return new Result(false,"添加失败，请选择套餐");
            }
            result=orderService.add(map,setmealIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"添加失败，请输入正确的手机号或身份证号");
        }
        return result;
    }

    @RequestMapping("/statusUpdate")
    public Result statusUpdate(Integer id){
        Result result=null;
        try {
            result=orderService.statusUpdate(id);
        }catch (Exception e){
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            orderService.delete(id);
            return new Result(true,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"删除失败");
        }
    }

    @RequestMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        try {
            //判断桶是否存在
            if (!minioUtils.bucketExists(prop.getBucketName())){
                //桶不存在，创建桶
                minioUtils.makeBucket(prop.getBucketName());
            }
            //桶存在，上传文件
            String orderFile = minioUtils.upload(file,prop.getBucketName());
            return new Result(true,"文件上传成功",orderFile);
//            System.out.println(filename);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"文件上传失败");
        }
    }

    @RequestMapping("/updateFile")
    public Result updateFile(@RequestBody Order order){
        Result result=null;
        try {
            result=orderService.updateFile(order);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"结果上传失败，请刷新重试");
        }
    }

    @RequestMapping("/findByPhoneNumber")
    public Result findByPhoneNumber(@CookieValue("login_member_telephone") String telephone){

        try {
            List<Order> orderList=orderService.findByPhoneNumber(telephone);
            return new Result(true,"获取订单信息成功",orderList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"获取订单信息失败，请稍后重试");
        }
    }

    @RequestMapping("/getOrderFile")
    public Result getOrderFile(@RequestBody Order order){
        try {
            //判断订单状态，如果已结束则可以下载，否则不能下载
            if (!"已结束".equals(order.getOrderStatus())){
                //订单未结束，即文件未上传
                return new Result(false,"结果查看/下载失败，请等待订单结束！！");
            }
            if (order.getOrderFile().isEmpty()){
                return new Result(false,"结果查看/下载失败，可能还未上传，请稍后重试！！");
            }
            //订单已结束
            return new Result(true,"结果查看/下载成功，请耐心等待！！");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"结果查看/下载失败，可能还未上传，请稍后重试！！");
        }
    }

//    @RequestMapping("/downloadFile")
//    public  void downloadFile(@RequestBody Order order, HttpServletResponse res){
//        try {
//            if (!"已结束".equals(order.getOrderStatus())){
//                //订单未结束，即文件未上传
//                return;
//            }
//            if (order.getOrderFile()==null){
//                return;
//            }
//            //调用minio工具类下载文件
//            minioUtils.download(order.getOrderFile(),res);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }

}